from datetime import datetime, timedelta, timezone

from fastapi import Depends, HTTPException,status
import jwt
from ..dependencies import oauth2_scheme

#生成方法opensssl rand -hex 32
SECRET_KEY="0e050326f807c1777c2dd854be285e435062186db1695e5a1458752a7535d0be"
ALGORITHM="HS256"
# ACCESS_TOKEN_EXPIRE_MINUTES=30

def create_token(data: dict):
    to_encode=data.copy()
    # to_encode.update({"exp":datetime.now(timezone.utc)+timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)})
    encoded_jwt=jwt.encode(
        to_encode,  # token传输内容
        SECRET_KEY,
        algorithm=ALGORITHM
    )
    return encoded_jwt
# def get_user_token(token:str=Depends(oauth2_scheme)):
#     print(token)
#     payload=jwt.decode(
#             token,
#             SECRET_KEY,
#             algorithms=[ALGORITHM]
#         )
#     return payload
def get_user_token(token:str=Depends(oauth2_scheme)):
    # print(token)
    try:
        payload=jwt.decode(
                token,
                SECRET_KEY,
                algorithms=[ALGORITHM]
            )
    except jwt.ExpiredSignatureError:
        raise HTTPException(
            status_code=status.HTTP_410_GONE,
            detail="Token过期",
            headers={"WWW-Authenticate":"Bearer"}
        )
    return payload

def get_username(token=Depends(get_user_token)):
    user_name=token['username']
    if user_name is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail="user_name is required")
    return user_name

